import {login, getUserInfo, logOut} from '@/api/api2login'
import {getToken, setToken, removeToken, getUsetType, setUsetType} from '@/utils/auth'
import {constantRoutes} from '@/router'
import Layout from '@/layout'
import CryptoJS from '@/utils/crypto'

const state = {
    token: getToken(), // 当前用户token
    userInfo: [], // 用户信息
    routes: [], // 路由列表
    roles: [] // 权限信息
}
const mutations = {
    // 设置token
    SET_TOKEN: (state, data) => {
        state.token = data
    },
    // 设置用户信息
    SET_USER_INFO: (state, data) => {
        state.userInfo = data
    },
    // 获取用户权限数组
    SET_ROUTERS: (state, needRoutes) => {
        state.routes = constantRoutes.concat(needRoutes)
    },
    // 设置用户权限
    SET_ROLES: (state, roles) => {
        state.roles = roles
    }
}
const actions = {
    // 登录
    async login({commit, dispatch}, {form}) {
        const obj = Object.keys(form)
        if (obj.length !== 0) {
            // 将用户名密码加密
            const username = CryptoJS.Encrypt(form.username);
            const password = CryptoJS.Encrypt(form.password);
            //【API请求】-----登录
            const res = await login({username: username, password: password, code: form.code, userType: form.userType})
            try {
                if (res.code === 0) {
                    const {data} = res
                    commit('SET_TOKEN', data.access_token)
                    setToken(data.access_token)
                    setUsetType(form.userType)
                }
                return await Promise.resolve(res)
            } catch (e) {
                console.log(e);
                // dispatch('logOut')
                throw e
            }
        }
    },
    // 获取用户信息
    async getInfo({commit, state, dispatch}) {
        let needRoutes
        console.log(getUsetType())
        const res = await getUserInfo({userType: getUsetType()})
        try {
            if (res.code === 0) {
                needRoutes = formatRoutes(res.data.menuList) // 筛选具有权限的数组项
                commit('SET_USER_INFO', res.data)
                commit('SET_ROLES', res.data.menuCodes)
                commit('SET_ROUTERS', needRoutes) // 路由结构重组
            } else {
                dispatch('logOut')
            }
        } catch (e) {
            console.log(e)
        }
        return Promise.resolve(needRoutes)
    },

    /* 更新用戶信息 （用户相关信息更改之后） */
    async updateUserInfo({commit, state}) {
        try {
            const res = await getUserData()
            if (res.code === 0) {
                commit('SET_USER_INFO', res)
            }
        } catch (e) {
            console.log(e)
        }
    },
    // // 获取用户权限信息
    // async generateRoutes({ commit, dispatch }) {
    //         const res = await getMenuListByUser()
    //         let needRoutes
    //         try {
    //             if (res.code === 0) {
    //                 needRoutes = formatRoutes(res.data) // 筛选具有权限的数组项
    //                 commit('SET_ROUTERS', { needRoutes }) // 路由结构重组
    //             }
    //         } catch (e) {
    //             console.log(e)
    //         }
    //         return Promise.resolve(needRoutes)
    // },
    // // 权限按钮信息
    // async getRoles({ commit, dispatch }, id) {
    //     const { data } = await getMenuCodesByRoleId({ roleId: id })
    //     commit('SET_ROLES', data)
    // },
    // 同步登出
    logOut({commit}) {
        commit('SET_TOKEN', '')
        commit('SET_USER_INFO', {})
        //location.reload()
        logOut().then(res => {
            console.log(res);
        })
        removeToken()
    }
}
// 处理路由结构信息
const formatRoutes = (menuList) => {
    const tempRouters = []

    // 循环遍历后台返回的菜单列表
    menuList.forEach(item => {
        var menu = item

        // 定义顶级菜单
        var parent = {
            hidden: menu.showFlag === 0,
            path: '/' + menu.pageUrl,
            component: Layout,
            redirect: 'noRedirect',
            alwaysShow: true,
            name: menu.code,
            meta: {
                title: menu.name,
                icon: menu.icon
            },
            children: []
        }

        // 定义二级菜单数组
        var children = []

        // 循环遍历顶级菜单的子级
        for (var i = 0; i < menu.children.length; i++) {
            var childMenu = menu.children[i]
            const tempcomponentPath = childMenu.pageUrl

            // 定义二级菜单项
            var obj

            // 遍历二级菜单的子级
            if (childMenu.children.length > 0) {
                obj = {
                    hidden: childMenu.showFlag === 0,
                    path: childMenu.code,
                    component(resolve) {
                        require(['@/layout/publish-center'], resolve)
                    },
                    redirect: childMenu.children[0].pageUrl,
                    name: childMenu.name,
                    meta: {title: childMenu.name, noCache: true, icon: childMenu.icon}
                }

                // 定义三级菜单数组
                var subchildren = []
                for (var j = 0; j < childMenu.children.length; j++) {
                    const subChildMenu = childMenu.children[j]
                    var subObj = {
                        hidden: childMenu.showFlag === 0,
                        path: subChildMenu.pageUrl,
                        component(resolve) {
                            require(['@/views/' + subChildMenu.pageUrl], resolve)
                        },
                        name: subChildMenu.name,
                        meta: {title: subChildMenu.name, noCache: true, icon: subChildMenu.icon}
                    }
                    // 三级菜单信息存入
                    subchildren.push(subObj)
                }
                obj.children = subchildren
            } else {
                obj = {
                    hidden: childMenu.showFlag === 0,
                    path: childMenu.pageUrl,
                    component(resolve) {
                        require(['@/views/' + tempcomponentPath], resolve)
                    },
                    name: childMenu.name,
                    meta: {title: childMenu.name, noCache: true, icon: childMenu.icon}
                }
            }

            // 二级菜单数组存入二级菜单项
            children.push(obj)
        }
        parent.children = children

        // 一级菜单新存入
        tempRouters.push(parent)
    })
    const route = [
        {
            path: '*',
            redirect: '/404',
            hidden: true
        },
        {
            path: '/404',
            component: () => import('@/views/error-page/404'),
            hidden: true
        }
    ]
    return [...tempRouters, ...route]
}
export default {
    namespaced: true, // 解决不同模块冲突问题
    state,
    mutations,
    actions
}
